'use strict';

var _interopRequireDefault = require('@babel/runtime/helpers/interopRequireDefault');
Object.defineProperty(exports, '__esModule', {
  value: true,
});
exports.default = void 0;
var _toConsumableArray2 = _interopRequireDefault(
  require('@babel/runtime/helpers/toConsumableArray'),
);
var _slicedToArray2 = _interopRequireDefault(require('@babel/runtime/helpers/slicedToArray'));
var _react = require('react');
var useList = function useList(opts) {
  var _ref = opts || {},
    _ref$initialDataSourc = _ref.initialDataSource,
    initialDataSource = _ref$initialDataSourc === void 0 ? [{}] : _ref$initialDataSourc,
    onChange = _ref.onChange,
    onAddOrRemove = _ref.onAddOrRemove;
  var _useState = (0, _react.useState)(initialDataSource),
    _useState2 = (0, _slicedToArray2.default)(_useState, 2),
    dataSource = _useState2[0],
    setDataSource = _useState2[1];
  var countRef = (0, _react.useRef)(0);
  var add = function add(item) {
    dataSource.push(item || {});
    changeDataSource((0, _toConsumableArray2.default)(dataSource));
    onAddOrRemove && onAddOrRemove();
  };
  var remove = function remove(item) {
    countRef.current = countRef.current + 1;
    if (typeof item === 'number') {
      dataSource.splice(item, 1);
      changeDataSource((0, _toConsumableArray2.default)(dataSource));
    } else {
      var newDataSource = dataSource.filter(function (it) {
        return item !== it;
      });
      changeDataSource(newDataSource);
    }
    onAddOrRemove && onAddOrRemove();
  };
  var changeDataSource = function changeDataSource(newDataSource) {
    setDataSource(newDataSource);
    onChange && onChange(newDataSource);
  };
  return {
    dataSource: dataSource,
    setDataSource: changeDataSource,
    add: add,
    remove: remove,
    mainKey: countRef.current,
  };
};
var _default = useList;
exports.default = _default;
